import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { ConfigProvider } from 'antd';
import { useTranslation } from 'react-i18next';
import enUS from 'antd/es/locale/en_US';
import zhCN from 'antd/es/locale/zh_CN';
import jaJP from 'antd/es/locale/ja_JP';
import './locales'; // 引入 i18next 配置文件
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { persistor, store } from '@/store';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';
import 'dayjs/locale/ja';
import Application from './App';
import './index.css'; 
import 'mac-scrollbar/dist/mac-scrollbar.css'; // 引入 mac-scrollbar 样式
import { WebSocketProvider } from './WebSocketContext.jsx'; 
import { useWebSocket } from '@/WebSocketContext';
import Cookies from 'js-cookie';

const App = () => {
  const { t, i18n } = useTranslation(); // i18n hook，用于国际化切换
  const [locale, setLocale] = useState(enUS); // 默认语言为中文
  const { connectWebSocket } = useWebSocket();

  useEffect(() => {
    const savedLanguage = localStorage.getItem('language') || 'en';  // 获取本地保存的语言，默认英文
    i18n.changeLanguage(savedLanguage);  // 切换到保存的语言
  }, [i18n]);
  
  useEffect(() => {
    const currentLang = i18n.language;
    switch (currentLang) {
      case 'zh_CN':
        setLocale(zhCN);
        dayjs.locale('zh-cn');
        break; 
      case 'ja':
        setLocale(jaJP);
        dayjs.locale('ja');
        break;
      default:
        setLocale(enUS);
        dayjs.locale('en');
        break;
    }
  }, [i18n.language]);

  useEffect(() => {
    const token = Cookies.get('token');
    if (token) {
      connectWebSocket(token);
    }
  }, [connectWebSocket]);
  return (
    <ConfigProvider
      locale={locale}
      theme={{
        cssVar: true,
        token: {
          colorPrimary: '#316AB9', // 自定义主色调
          borderRadius: 4,
        },
      }}
    >
      <Application />
    </ConfigProvider>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
    <WebSocketProvider>
      <Router>
        <App />
      </Router>
    </WebSocketProvider>
    </PersistGate>
  </Provider>
);
